<template>
  <div ref="flowRef" class="dataFlow"></div>
</template>

<script setup>
import G6 from '@antv/g6'
import { nextTick, onUnmounted } from 'vue-demi'
const lineDash = [4, 2, 1, 2]

const props = defineProps({
  data: {
    type: String,
    default: {}
  }
})

const flowRef = ref(null)

onMounted(() => {})

const graphObj = ref(null)

//监听数据变化
watch(
  () => props.data,
  (newVal, oldVal) => {
    console.log('newVal', newVal)
    console.log('oldVal', oldVal)
    if (newVal !== oldVal) {
      console.log('数据变化了')
      init()
    }
  },
  {
    deep: true
  }
)

const dataSourceComponent = `
    <group>
      <rect>
        <rect style={{
          width: 420,
          height: 50,
          fill: {{data.color}},
          radius: [12, 12, 0, 0],
          cursor: 'move',
        }} draggable="true">
          <text style={{
            marginTop: 16,
            marginLeft: 210,
            textAlign: 'center',
            fontWeight: 'bold',
            fontSize: 20,
            fill: '#fff' }}>{{datasourceName}}</text>
        </rect>
        <rect style={{
          width: 420,
          height: 130,
          stroke: {{data.color}},
          fill: #ffffff,
          radius: [0, 0, 12, 12],
        }}>
          <text style={{ marginTop: 14, marginLeft: 16, fill: '#333', fontSize: 20, }}>节点类型: 数据源</text>
            <text style={{ marginTop: 35, marginLeft: 16, fill: '#333', fontSize: 20, }}>类型: {{data.type}}</text>
            <text style={{ marginTop: 56, marginLeft: 16, fill: '#333', fontSize: 20, }}>用户名: {{data.username}}</text>


        </rect>
      </rect>
    </group>`

const indexComponent = `
    <group>
      <rect>
        <rect style={{
          width: 420,
          height: 50,
          fill: {{data.color}},
          radius: [12, 12, 0, 0],
          cursor: 'move',
        }} draggable="true">
          <text style={{
            marginTop: 16,
            marginLeft: 210,
            textAlign: 'center',
            fontWeight: 'bold',
            fontSize: 20,
            fill: '#fff' }}>{{datasourceName}}</text>
        </rect>
        <rect style={{
          width: 420,
          height: 45,
          stroke: {{data.color}},
          fill: #ffffff,
          radius: [0, 0, 12, 12],
        }}>

            <text style={{ marginTop: 14, marginLeft: 16, fill: '#333', fontSize: 20, }}>节点类型: 指标</text>



        </rect>
      </rect>
    </group>`

const catalogueComponent = `
    <group>
      <rect>
        <rect style={{
          width: 420,
          height: 50,
          fill: {{data.color}},
          radius: [12, 12, 0, 0],
          cursor: 'move',
        }} draggable="true">
          <text style={{
            marginTop: 16,
            marginLeft: 210,
            textAlign: 'center',
            fontWeight: 'bold',
            fontSize: 20,
            fill: '#fff' }}>{{datasourceName}}</text>
        </rect>
        <rect style={{
          width: 420,
          height: 45,
          stroke: {{data.color}},
          fill: #ffffff,
          radius: [0, 0, 12, 12],
        }}>

            <text style={{ marginTop: 14, marginLeft: 16, fill: '#333', fontSize: 20, }}>节点类型: 目录</text>



        </rect>
      </rect>
    </group>`

const init = () => {
  try {
    G6.registerNode('card-node', (cfg) => {
      console.log('cfg')
      console.log(cfg)
      if (cfg.businessType === 'index') {
        return indexComponent
      } 
      if(cfg.businessType === 'dataSource' || (cfg.businessType === '')) {
        return dataSourceComponent
      }
      if(cfg.businessType === 'catalog') {
        return catalogueComponent
      }
    })

    G6.registerEdge(
      'line-dash',
      {
        afterDraw(cfg, group) {
          // get the first shape in the group, it is the edge's path here=
          const shape = group.get('children')[0]
          let index = 0
          // Define the animation
          shape.animate(
            () => {
              index++
              if (index > 9) {
                index = 0
              }
              const res = {
                lineDash,
                lineDashOffset: -index
              }
              // returns the modified configurations here, lineDash and lineDashOffset here
              return res
            },
            {
              repeat: true, // whether executes the animation repeatly
              duration: 3000 // the duration for executing once
            }
          )
        }
      },
      'cubic' // extend the built-in edge 'cubic'
    )
    const data = props.data

    console.log('data')
    console.log(data)

    const container = flowRef.value
    const width = container.scrollWidth
    const height = container.scrollHeight || 500
    const graph = new G6.Graph({
      container,
      width,
      height,
      fitView: true,
      modes: {
        default: ['drag-canvas', 'drag-node', 'zoom-canvas']
      },
      layout: {
        type: 'dagre',
        rankdir: 'LR',
        align: 'DL',
        nodesepFunc: () => 90,
        ranksepFunc: () => 200
      },
      defaultNode: {
        type: 'card-node',
        style: {
          lineWidth: 2,
          stroke: '#5B8FF9',
          fill: '#C6E5FF'
        },
        linkPoints: {
          top: true,
          bottom: true,
          left: true,
          right: true,
          size: 5,
          fill: '#fff',
          lineWidth: 1,
          stroke: '#1890FF'
        }
      },
      defaultEdge: {
        type: 'line-dash',
        size: 4,
        style: {
          endArrow: true,
          stroke: '#2ed573'
        }
      }
    })

    //Minimap
    const minimap = new G6.Minimap({
      size: [150, 100],
      className: 'minimap',
      type: 'delegate'
    })
    graph.addPlugin(minimap)

    // //节点默认不展开
    // graph.get('group').on('click', (e) => {
    //   const item = e.item
    //   const name = item.getModel().datasourceName
    //   if (item.getModel().expanded) {
    //     graph.updateItem(item, {
    //       expanded: false
    //     })
    //   } else {
    //     graph.updateItem(item, {
    //       expanded: true
    //     })
    //   }
    // })

    graphObj.value = graph

    graph.data(data)
    graph.render()

    function handleNodeClick(event) {
      const item = event.item
      // animately move the graph to focus on the item.
      graph.focusItem(item)
    }

    // listen to the node click event
    graph.on('node:click', handleNodeClick)

    if (typeof window !== 'undefined')
      window.onresize = () => {
        if (!graph || graph.get('destroyed')) return
        if (!container || !container.scrollWidth || !container.scrollHeight) return
        graph.changeSize(container.scrollWidth, container.scrollHeight)
      }
  } catch (error) {
    debugger
    console.log('error')
  }
}

const changeSize = () => {
  const container = flowRef.value

  if (!graphObj.value || graphObj.value.get('destroyed')) return
  if (!container || !container.scrollWidth || !container.scrollHeight) return
  graphObj.value.changeSize(container.scrollWidth, container.scrollHeight)

  graphObj.value.fitView()
}

//导出方法
defineExpose({
  changeSize
})
</script>

<style lang="scss" scoped>
.dataFlow {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
